#include "BoardConf.h"
#include "Montion.h"
#include "BoardAssembly.h"
#include "AmbientLight.h"
#include "MessageRouter.h"

BoardConf::BoardConf(IArduino& a, MessageRouter& router, ServiceFactory& factory, const String& name, ILogger& logger) 
: Service(a, router, name, logger), _state(READY), _router(router), _arduino(a), _factory(factory){
}

bool BoardConf::onItem(const String& name, const String& value){
	switch(_state){
			  case READY:
				  if(name == F("conf")){
					  if(value == F("removeAll")){
						  removeAll();
						  return false;
					  } else{
						  _command = value;
						  _state = BOARD_NAME_READ;
						  return true;
					  }
				  }
				  else	
					  return false;
			  case BOARD_NAME_READ:
				  if((name == F("node"))&&(value == name_)){
					  _state = DATA_READ;
					  return true;
				  }
				  else{
					_state = READY;
					  return false;
				  }
				  break;
			  case DATA_READ:
				  if(name == F("type")){
					  _serviceType = value;
					  return true;
				  }
				  if(name == F("name")){
					  _serviceName = value;
					  if(_command == F("remove")){
						  removeService(value);
						  break;
					  }
					  return true;
				  }
				  if(name == F("pin")){
					  _pin = value.toInt();
					  createService();
				  }
				  if(name == F("buttonTrigger")){
					  _buttonTrigger = value;
					  return true;
				  }
				  if(name == F("montionTrigger")){
					  _montionTrigger = value;
					  return true;
					}
				  if(name == F("lightCircuit")){
					  _lightCircuit = value;
					  createService();
					}
				  break;
	}
	_state = READY;
	return false;
}
void BoardConf::removeService(const String& serviceName){
	IService* s = _router.removeService(serviceName);
	delete s;
}
void BoardConf::removeAll(){
	int size = _router.getServicesSize();
	for(int i = size-1; i >= 0; --i){
		const String& name(_router.getService(i)->getName());
		if(!_router.getService(i)->isInfrastructure()){
			_router.removeService(name);
		}
	}
}
bool BoardConf::isInfrastructure() const{
	return true;
}

void BoardConf::createService(){
	Service* s = 0;
	if(_serviceType == F("Montion")){
		s = &_factory.createMontion(_serviceName, _pin);
	} else if(_serviceType == F("AmbientLight")){
		s = &_factory.createAmbient(_serviceName, _buttonTrigger, _montionTrigger, _lightCircuit);
	} else if(_serviceType == F("SimpleLight")){
		s = &_factory.createSimpleLight(_serviceName, _buttonTrigger, _lightCircuit);
	} else if(_serviceType == F("Button")){
		s = &_factory.createButton(_serviceName, _pin);
	} else if(_serviceType == F("LightCircuit")){
		s = &_factory.createLight(_serviceName, _pin);
	}
	if(s!=0){
		_router.addService(*s);
	}
}